package algorithm.graph.base;

import algorithm.graph.adjacencymatrix.AdjacencyMatrixGraph;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.Predicate;

public class GraphUtil {
    public static List<Edge> getNonDirectedGraphEdgeList(AdjacencyMatrixGraph graph) {
        int nodeCount = graph.getNodeCount();
        int[][] graphData = graph.getGraphData();
        List<Edge> edgeList = new ArrayList<>();
        for (int i = 0; i < nodeCount; i++) {
            for (int j = i + 1; j < nodeCount; j++) {
                int weight = graphData[i][j];
                if (weight != -1) {
                    Edge edge = new Edge(i, j, weight);
                    edgeList.add(edge);
                }
            }
        }
        return edgeList;
    }

    public static List<Edge> getDirectedGraphEdgeList(AdjacencyMatrixGraph graph) {
        int nodeCount = graph.getNodeCount();
        int[][] graphData = graph.getGraphData();
        List<Edge> edgeList = new ArrayList<>();
        for (int i = 0; i < nodeCount; i++) {
            for (int j = 0; j < nodeCount; j++) {
                int weight = graphData[i][j];
                if (weight != -1) {
                    Edge edge = new Edge(i, j, weight);
                    edgeList.add(edge);
                }
            }
        }
        return edgeList;
    }

    public static <T> void removeItemFromList(List<T> dataList, Predicate<T> predicate) {
        Iterator<T> iterator = dataList.iterator();
        while (iterator.hasNext()) {
            T edge = iterator.next();
            if (predicate.test(edge)) {
                iterator.remove();
            }
        }
    }

    public static void printGraph(AdjacencyMatrixGraph graph) {
        System.out.println("节点数量: " + graph.getNodeCount());
        System.out.println(Arrays.deepToString(graph.getGraphData()).replace("],", "],\n").replace("-1", " "));
    }
}
